<template>
  <div class="w100 flex-x flex-top h-full">
    <!-- <TreeBox style="width: 18%"></TreeBox> -->
    <div style="width: 100%;height: 100%;">
      <Search :deviceRow="controlDeviceInfo" @onSubmit="onSearch"></Search>
      <CheckParameter
        ref="checkParameterRef"
        @changeGroup="changeGroup"
        @changeBox="changeBox"
        :list="attributesList"
        style="margin: 10px 0"
      ></CheckParameter>
      <CurveChart
        ref="curveChartRef"
        class="height: 100%;"
        :option="option"
      ></CurveChart>
    </div>
  </div>
</template>

<script>
import TreeBox from "../../deviceOperation/components/TreeBox.vue";
import Search from "./components/Search.vue";
import CheckParameter from "./components/CheckParameter.vue";
import CurveChart from "./components/CurveChart.vue";
import { renderSql, setIntervalTime, COLORS } from "./js/constent";
import { mixinOpenedKey } from "@/mixin/openedKey.js";
import _ from "lodash";
import { get4hour } from "@/utils/currentDate";
import { formatDate } from "@/filter/index";
import { mapGetters } from "vuex";
import { getDeviceAttributes } from "@/api/deviceType";
import { restSql } from "@/api/taos";
import { POINT_CHART_TYPES } from "@/utils/local";
// 值的下标
const VAL_INDEX = 2;
// 时间的下标
const TIME_INDEX = 0;

export default {
  mixins: [mixinOpenedKey],
  props: {
    activeName: {
      type: String,
      default: ""
    }
  },
  components: { TreeBox, Search, CheckParameter, CurveChart },
  computed: {
    tenant() {
      return this.$store.state.user.tenant;
    },
    ...mapGetters(["controlDeviceInfo"]),
    // 设备toekn
    deviceToken() {
      return this.controlDeviceInfo.token;
    },
    assignmentToken() {
      return this.controlDeviceInfo.assignmentToken;
    }
  },
  data() {
    return {
      attributesList: [],
      intervalTime: "10s",
      lcurveLoading: false,
      area123Curve: [],
      option: {
        color: COLORS,
        dataZoom: [
          {
            show: true,
            height: 25,
            xAxisIndex: [0],
            bottom: 15,
            start: 0,
            end: 100,
            handleSize: "110%"
          },
          {
            type: "inside",
            show: true,
            height: 15,
            start: 1,
            end: 100
          }
        ],
        tooltip: {
          trigger: "axis",
          confine: true, //解决浮窗被截断问题 ,把浮窗限制在图标内,不然超出会被遮挡
          show: true,
          formatter: function(params) {
            var str = "";
            for (var i = 0, l = params.length; i < l; i++) {
              // 小圆点
              const bgStr = `<span style='margin-right: 6px;display:inline-block;width:10px;height:10px;border-radius:10px;background-color:${params[i].color};'></span>`;
              str +=
                bgStr +
                params[i].seriesName +
                ": " +
                (params[i].value || "--") +
                params[i].data.unit +
                "<br />";
            }
            return params[0].axisValue + "<br />" + str;
          },
          axisPointer: {
            type: "cross",
            crossStyle: {
              color: "#fff"
            },
            lineStyle: {
              type: "dashed"
            }
          }
        },
        grid: {
          left: "25",
          right: "25",
          bottom: 50,

          top: "65",
          containLabel: true
        },
        legend: {
          // padding: [0, 0, 0, 0],
          orient: "horizontal",
          //   icon: "rect",
          show: true,
          textStyle: {
            color: "#fff"
          },
          left: 20,
          top: 10
        },
        xAxis: {
          type: "category",
          data: [],
          splitLine: {
            show: false
          },
          axisTick: {
            show: false
          },
          axisLabel: {
            color: "#fff",
            textStyle: {
              fontSize: 12
            }
          },
          axisLine: {
            show: false
          }
        },
        yAxis: [],
        series: []
      },
      searchForm: {}
    };
  },
  mounted() {},
  watch: {
    deviceToken: {
      async handler(newVal) {
        if (newVal && this.activeName == "历史曲线查询") {
          this.$nextTick(async () => {
            // 生成曲线之前 清空图表和筛选参数
            this.clean();
            // 获取筛选变量点位
            await this.getDeviceAttributes();
            // 当前设备存在点位 就默认选中第一个
            if (this.attributesList.length) {
              // 如果有数据且不存在选中的,就默认选中第一个
              this.resetChert(this.attributesList[0]);
            } else {
              this.$refs.checkParameterRef.checkList = [];
            }
          });
        }
      },
      immediate: true,
      deep: true
    }
  },
  methods: {
    // 生成Y轴
    renderyAxis(name) {
      return {
        position: "left",
        type: "value",
        name: name,
        offset: 0,
        nameTextStyle: {
          color: "#fff"
        },
        axisLabel: {
          color: "#fff",
          textStyle: {
            fontSize: 12
          }
        },
        splitLine: {
          show: true,
          lineStyle: {
            color: "#F3F4F4"
          }
        },
        axisTick: {
          show: false
        },
        axisLine: {
          show: false
        }
      };
    },
    clean() {
      this.option.xAxis.data = [];
      this.option.series = [];
      this.$refs.checkParameterRef.checkList = [];
      this.$refs.curveChartRef.disposeChart();
    },
    async getDeviceAttributes() {
      return new Promise(async (resolev, reject) => {
        const res = await getDeviceAttributes(
          {
            page: 1,
            pageSize: 1000000
          },
          this.deviceToken
        );
        this.attributesList = res.data.results.filter(item => {
          let c = item.isChart.slice(",");
          return c.includes(POINT_CHART_TYPES[1].key);
        });
        resolev();
      });
    },
    // 获取sql查询的原始数据
    getSqlData(params) {
      return new Promise((resolev, reject) => {
        const sqlStr = renderSql({
          ...params,
          tenantToken: this.tenant.token,
          assignmentToken: this.assignmentToken
        });
        if (!sqlStr) {
          reject("暂无数据");
        }
        restSql(sqlStr)
          .then(res => {
            const data = res.data.data;
            if (!data.length) {
              // 选中之后,如果没查出来数据,取消选中
              const index = this.$refs.checkParameterRef.checkList.findIndex(
                item => item == params.type
              );
              if (index !== -1) {
                this.$refs.checkParameterRef.checkList.splice(index, 1);
              }
              this.$msg("暂无数据");
              reject("暂无数据");
            }
            // 曲线数据
            const dateList = data.map(function(item) {
              return item[VAL_INDEX];
            });
            //时间轴
            const timeList = data.map(item => {
              return this.$moment(item[TIME_INDEX]).format(
                "YYYY-MM-DD HH:mm:ss"
              );
            });

            resolev({
              xAxis: timeList,
              series: {
                name: params.label,
                type: "line",
                smooth: true,
                showSymbol: false,
                data: dateList
              }
            });
          })
          .catch(err => {
            this.$msg("暂无数据");
            // 选中之后,如果没查出来数据,取消选中
            const index = this.$refs.checkParameterRef.checkList.findIndex(
              item => item == params.type
            );
            if (index !== -1) {
              this.$refs.checkParameterRef.checkList.splice(index, 1);
            }
            reject(err);
          });
      });
    },

    // Reset图表  默认选中第一个
    resetChert(attr) {
      // 不存在的重置
      if (!attr) {
        this.option.xAxis.data = [];
        this.option.series = [];
        this.$refs.curveChartRef.disposeChart();
        return;
      }
      this.$nextTick(() => {
        if (this.$refs.checkParameterRef.checkList.length == 0) {
          this.$refs.checkParameterRef.checkList = [attr.token];
        }
        setTimeout(() => {
          this.changeBox({
            ...attr,
            isCheck: true
          });
        }, 500);
      });
    },
    //  搜索
    async onSearch(search) {
      this.$refs.checkParameterRef.checkList = [];
      this.option.xAxis.data = [];
      this.option.series = [];
      if (search) {
        this.searchForm = _.cloneDeep(search);
        console.log("搜索参数 :>> ", this.searchForm);
        // 设置当前开始时间和结束时间的间隔
        if (!setIntervalTime(this.searchForm)) {
          this.$msg("请选择小于一年的时间间隔");
          return;
        }
        this.intervalTime = setIntervalTime(this.searchForm);
        console.log("时间间隔 :>> ", this.intervalTime);
        this.$nextTick(() => {
          // 存在点位,就默认选中第一个
          if (this.attributesList.length) {
            this.resetChert(this.attributesList[0]);
          } else {
            this.$refs.checkParameterRef.checkList = [];
          }
        });
      } else {
        // 重置
        this.resetChert();
        this.searchForm = {};
        this.intervalTime = "10s";
      }
    },
    // renderParams 返回筛选的时间参数参数
    renderTimeParams(params) {
      return {
        ...params
      };
    },
    changeGroup(list) {},
    // 设置多个y轴的间距
    setYaxisOffset() {
      let offset = 0;
      this.option.yAxis.forEach(item => {
        item.offset = offset;
        offset += 38;
      });
    },
    // 获取开始结束时间
    getStartEndData() {
      return {
        startTime: this.searchForm.startDate
          ? this.searchForm.startDate
          : this.$moment()
              .subtract(4, "hour")
              .format("YYYY-MM-DD HH:mm:ss"),
        endTime: this.searchForm.endDate
          ? this.searchForm.endDate
          : this.$moment().format("YYYY-MM-DD HH:mm:ss")
      };
    },
    async changeBox(row) {
      // val就是 当前选中的key 例: meter1RealTemp
      // name就是 当前选中的label 例: 温控表测量温度
      // isCheck 是否选中
      // yAxisIndex 左右y轴的下标 0 左边 1右边
      // unit y轴的单位轴
      const { token, name, isCheck, unit, deviceEventType } = row;
      console.log("当前选中 :>> ", row);
      // 开始时间和结束时间不存在 默认取4小时的
      try {
        if (isCheck) {
          const obj = await this.getSqlData({
            type: token,
            intervalTime: this.intervalTime,
            label: name,
            deviceEventType,
            ...this.getStartEndData()
          });
          console.log("首次获取的数据 :>> ", obj.series);
          // 拼接Y轴数据
          const yaxisIndex = this.option.yAxis.findIndex(
            item => item.name == unit
          );
          // 不存在当前的单位Y轴 就添加新的
          if (yaxisIndex == -1) {
            this.option.yAxis.push(this.renderyAxis(unit));
          }
          //时间轴
          this.option.xAxis.data = obj.xAxis;
          // 添加一根曲线
          this.option.series.push({
            name: name,
            type: "line",
            smooth: true,
            showSymbol: false,
            data: obj.series.data.map(s => {
              return {
                value: s,
                unit
              };
            }),
            // 当前折线对应的y轴单位轴
            yAxisIndex: this.option.yAxis.findIndex(item => item.name == unit),
            unit
          });
        } else {
          // 删除折线
          const index = this.option.series.findIndex(i => i.name == name);
          this.option.series.splice(index, 1);
          // 从新设置 yAxisIndex
          this.setyAxisIndex(unit);
        }
      } catch (error) {
        console.log("没查出数据 :>> ", error);
      }
      // 设置y轴间距
      this.setYaxisOffset();
    },
    delYaxis() {},
    // 从新设置 yAxisIndex
    setyAxisIndex(unit) {
      // 判断当前选中的单位 是否存在数据中
      const isUnit = this.option.series.find(item => item.unit == unit);
      // 如果不存在,就是当前的单位轴删除
      if (!isUnit) {
        this.option.yAxis.splice(
          this.option.yAxis.findIndex(item => item.name == unit),
          1
        );
      }
      // 从新设置对应的单位轴下标
      if (this.option.series.length) {
        this.option.series.forEach(ser => {
          this.option.yAxis.forEach((y, i) => {
            if (ser.unit == y.name) {
              ser.yAxisIndex = i;
            } else {
            }
          });
        });
      }
    }
  }
};
</script>

<style lang="scss" scoped></style>
